
g_Instance = None

class LabelManager:

    def __init__(self):
        global g_Instance
        if g_Instance:
            raise("LabelManager init already")
        g_Instance = self
        self._projectName = "labels"
        self._sourceFilePath = ""
        self._width = 1280
        self._height = 780
        self._labels = {}

    def loadProject(self, projectFile):
        f = open(projectFile, "r")
        data = f.read()
        f.close()
        self._sourceFilePath = projectFile
        import json
        d = json.loads(data)
        self._projectName = d.get("project", "untitle")
        if "size" in d:
            self._width = d["size"]["width"]
            self._height = d["size"]["height"]
        if "labels" in d:
            self._labels = d["labels"]

    @staticmethod
    def instance():
        return g_Instance
    
    def setScreenSize(self, w, h):
        self._width = w
        self._height = h

    def getAllGroup(self):
        return list(self._labels.keys())

    def addGroup(self, name):
        if name in self._labels:
            raise Exception(f"group \"{name}\" already exist.")
        self._labels[name] = {}
        self.saveToFile()

    def getLabel(self, group, name):
        if group not in self._labels:
            return None
        for info in self._labels[group]:
            if name == info[0]:
                return info
        return None

    def renameGroup(self, oldname, newname):
        if oldname not in self._labels:
            return
        self._labels[newname] = self._labels.pop(oldname)
        

    def addLabel(self, group, name, x, y, w, h):
        if group not in self._labels:
            self._labels[group] = []
        self._labels[group].append((name, x, y, w, h))
        self.saveToFile()

    def removeLabel(self, group, name):
        if group not in self._labels:
            return
        for info in self._labels[group]:
            if name == info[0]:
                self._labels[group].remove(info)
                break
        self.saveToFile()
    
    def checkValidName(self, group, name):
        if group not in self._labels:
            return True
        for info in self._labels[group]:
            if name == info[0]:
                return False
        return True

    def getData(self):
        d = {
            "project": self._projectName,
            "size": {
                "width": self._width,
                "height": self._height,
            },
            "labels": self._labels,
        }
        import json
        data = json.dumps(d)
        return data

    def saveToFile(self):
        f = open(f"{self._projectName}_{self._width}_{self._height}.json", "w")
        data = self.getData()
        f.write(data)
        f.close()
        